package service

import (
	"encoding/json"
	"fmt"
	"gitcode.com/G-YT/iHealth25/server/global"
	"io"
	"io/ioutil"
	"net/http"
)

type wechatService struct{}

var WechatService = new(wechatService)

// 微信OpenID响应结构体
type wechatResponse struct {
	OpenID string `json:"openid"`
}

func (s *wechatService) GetOpenIDByCode(code string) (string, error) {
	// 构造微信API请求URL（参考微信官方文档）
	url := "https://api.weixin.qq.com/sns/jscode2session?" +
		"appid=" + global.GVA_CONFIG.WeiXin.AppID +
		"&secret=" + global.GVA_CONFIG.WeiXin.AppSecret +
		"&js_code=" + code +
		"&grant_type=authorization_code"
	// 发送HTTP请求
	fmt.Printf("url: %s\n", url)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer func(Body io.ReadCloser) {
		cErr := Body.Close()
		if cErr != nil {

		}
	}(resp.Body)
	// 解析响应
	body, _ := ioutil.ReadAll(resp.Body)
	var result wechatResponse
	if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
		return "", unmarshalErr
	}
	fmt.Printf("OpenID: %s\n", result.OpenID)
	return result.OpenID, nil
}
